<?php
/**
 * 平台日销售额 (平台基础销售额数据)
 */
namespace App\Logic\SalesAmazon;

use App\Models\Amazon\AmazonOrder;
use App\Models\Basics\AmazonCountry;
use App\Models\Basics\ExchangeRate;
use App\Models\Basics\SysPlat;
use App\Models\Product\ProductAmazonSku;
use App\Models\Product\ProductRakutenSku;
use App\Models\Product\ProductSku;
use App\Models\Rakuten\RakutenOrder;
use App\Models\SalesAmazon\SalesAmountDay;
use App\Models\Shopify\ShopifyOrder;
use Illuminate\Support\Facades\DB;
class SalesAmountDaily
{
    public static function init($days = 7)
    {
        $amazonPlat = SysPlat::PLAT_AMAZON;
        $shopifyPlat = SysPlat::PLAT_SHOPIFY;
        $rakutenPlat = SysPlat::PLAT_RAKUTEN;

        $i = 1;
        $country = [];
        while(true){
            if($i > $days)break;
            $time = strtotime("-{$i} days");
            $start = date('Y-m-d 00:00:00',$time);
            $end = date('Y-m-d 23:59:59',$time);
            $day = date('Ymd',$time);

            //DB::beginTransaction();
            //try{
                //amazon
                //清空平台日销售额表(amazon)
                SalesAmountDay::query()->where('plat_id',$amazonPlat)->where('day',$day)->update(['amount'=>0,'promotion_discount'=>0]);
                $currency = [];
                $sku = [];
                AmazonOrder::query()
                    ->where('purchase_date','>=',$start)
                    ->where('purchase_date','<=',$end)
                    ->where('order_status','>=',3)
                    ->where('order_status','<>',7)
                    ->select('id','amazon_order_id','marketplace_id')
                    ->orderBy('id')
                    ->chunk(500, function ($aOrders) use(&$country,&$currency,&$sku,$day,$time,$amazonPlat){
                        foreach ($aOrders as $aOrder){
                            if(!array_key_exists($aOrder->marketplace_id,$country)){
                                $country[$aOrder->marketplace_id] = AmazonCountry::getCountryIdByMarketplaceId($aOrder->marketplace_id);
                            }
                            $countryId = $country[$aOrder->marketplace_id];
                            foreach ($aOrder->items as $item){
                                if(is_null($item->currency))continue;
                                $amount = SalesAmountDay::query()
                                    ->where('plat_id',$amazonPlat)
                                    ->where('country_id',$countryId)
                                    ->where('seller_sku',$item->sku)
                                    ->where('day',$day)
                                    ->first();
                                if($amount){
                                    $amount->amount += ($item->price ?: 0);
                                    $amount->promotion_discount += ($item->promotion_discount ?: 0);
                                    $amount->save();
                                }else{
                                    if(!array_key_exists($item->currency,$currency)){
                                        $currency[$item->currency] = ExchangeRate::getRateOddsToRMB($item->currency,$time);
                                    }
                                    if(!array_key_exists($item->sku,$sku)){
                                        $pSkuId = ProductAmazonSku::query()->where('seller_sku',$item->sku)->value('psku_id');
                                        $sku[$item->sku] = $pSkuId ?: 0;
                                    }
                                    SalesAmountDay::query()->create([
                                        'plat_id'    => $amazonPlat,
                                        'country_id' => $countryId,
                                        'seller_sku' => $item->sku,
                                        'day' => $day,
                                        'account_id' => $item->account_id,
                                        'psku_id' => $sku[$item->sku],
                                        'amount' => $item->price ?: 0,
                                        'promotion_discount' => $item->promotion_discount ?: 0,
                                        'rate_odds' => $currency[$item->currency]
                                    ]);
                                }
                            }
                        }
                    });
                sleep(2);

                //shopify
                //清空平台日销售额表(shopify)
                SalesAmountDay::query()->where('plat_id',$shopifyPlat)->where('day',$day)->update(['amount'=>0,'promotion_discount'=>0]);
                $shopifyCountryId = 1; //US
                $shopifyCurrency = [];
                $shopifySku = [];
                ShopifyOrder::query()
                    ->where('purchase_at','>=',strtotime($start))
                    ->where('purchase_at','<=',strtotime($end))
                    ->orderBy('id')
                    ->chunk(500, function ($aOrders) use(&$shopifyCountryId,&$shopifyCurrency,&$shopifySku,$day,$time,$shopifyPlat){
                        foreach ($aOrders as $aOrder){
                            foreach ($aOrder->shopify_orders_items as $item){
                                if(is_null($item->currency))continue;
                                $amount = SalesAmountDay::query()
                                    ->where('plat_id',$shopifyPlat)
                                    ->where('country_id',$shopifyCountryId)
                                    ->where('seller_sku',$item->sku)
                                    ->where('day',$day)
                                    ->first();
                                if($amount){
                                    $amount->amount += ($item->price ?: 0);
                                    $amount->promotion_discount += ($item->discount_allocations ?: 0);
                                    $amount->save();
                                }else{
                                    if(!array_key_exists($item->currency,$shopifyCurrency)){
                                        $shopifyCurrency[$item->currency] = ExchangeRate::getRateOddsToRMB($item->currency,$time);
                                    }
                                    if(!array_key_exists($item->sku,$shopifySku)){
                                        //$pSkuId = ProductShopifySku::query()->where('seller_sku',$item->sku)->value('psku_id');
                                        $pSkuId = ProductSku::query()->where('psku_code',$item->sku)->value('id');
                                        $shopifySku[$item->sku] = $pSkuId ?: 0;
                                    }
                                    SalesAmountDay::query()->create([
                                        'plat_id'    => $shopifyPlat,
                                        'country_id' => $shopifyCountryId,
                                        'seller_sku' => $item->sku,
                                        'day' => $day,
                                        'account_id' => $item->account_id, //shopify账号
                                        'psku_id' => $shopifySku[$item->sku],
                                        'amount' => $item->price ?: 0,
                                        'promotion_discount' => $item->discount_allocations ?: 0,
                                        'rate_odds' => $shopifyCurrency[$item->currency]
                                    ]);
                                }
                            }
                        }
                    });
                sleep(2);

                //rakuten
                //清空平台日销售额表(rakuten)
                SalesAmountDay::query()->where('plat_id',$rakutenPlat)->where('day',$day)->update(['amount'=>0,'promotion_discount'=>0]);
                $rakutenCountryId = 12; //JP国家
                $rakutenCurrency = []; //JP货币汇率
                $rakutenSku = [];
                RakutenOrder::query()
                    ->where('order_datetime','>=',strtotime($start))
                    ->where('order_datetime','<=',strtotime($end))
                    ->where('order_progress','>=',300)
                    ->where('order_progress','<=',700)
                    ->orderBy('id')
                    ->chunk(500, function ($rOrders) use(&$rakutenCountryId,&$rakutenCurrency,&$rakutenSku,$day,$time,$rakutenPlat){
                        foreach ($rOrders as $rOrder){
                            foreach ($rOrder->rakuten_orders_items as $rakutenItem){
                                if(is_null($rakutenItem->currency))continue;
                                $amount = SalesAmountDay::query()
                                    ->where('plat_id', $rakutenPlat)
                                    ->where('country_id',$rakutenCountryId)
                                    ->where('seller_sku',$rakutenItem->platform_sku)
                                    ->where('day',$day)
                                    ->first();
                                if($amount){
                                    $amount->amount += ($rakutenItem->price ?: 0);
                                    $amount->promotion_discount += 0;
                                    $amount->save();
                                }else{
                                    if(!array_key_exists($rakutenItem->currency,$rakutenCurrency)){
                                        $rakutenCurrency[$rakutenItem->currency] = ExchangeRate::getRateOddsToRMB($rakutenItem->currency,$time);
                                    }
                                    if(!array_key_exists($rakutenItem->platform_sku,$rakutenSku)){
                                        $pSkuId = ProductRakutenSku::query()->where('seller_sku',$rakutenItem->platform_sku)->value('psku_id');
                                        $rakutenSku[$rakutenItem->platform_sku] = $pSkuId ?: 0;
                                    }
                                    SalesAmountDay::query()->create([
                                        'plat_id'    => $rakutenPlat,
                                        'country_id' => $rakutenCountryId,
                                        'seller_sku' => $rakutenItem->platform_sku,
                                        'day' => $day,
                                        'account_id' => $rakutenItem->account_id, //rakuten账号
                                        'psku_id' => $rakutenSku[$rakutenItem->platform_sku],
                                        'amount' => $rakutenItem->price ?: 0,
                                        'promotion_discount' => 0,
                                        'rate_odds' => $rakutenCurrency[$rakutenItem->currency]
                                    ]);
                                }
                            }
                        }
                    });

            //    DB::commit();
            //}catch (\Exception $e){
            //    DB::rollBack();
            //    report($e);
            //}

            echo $day.PHP_EOL;
            $i++;
            sleep(1);
        }
    }

    /**
     * 补录rakuten平台数据
     * @param $startDate
     * @param $endDate
     * @return false
     */
    public static function initBack($startDate, $endDate)
    {
        $shopifyPlat = SysPlat::PLAT_SHOPIFY;

        $startDates = $startDate == 'null' ? date('Y-m-d', strtotime("-7 days")) : $startDate; //开始时间
        $endDates = $endDate == 'null' ? date('Y-m-d', strtotime("-1 days")) : $endDate; //结束时间
        if (!strtotime($startDates) || !strtotime($endDates)) return false;

        $bof = strtotime($startDates); //开始
        $eof = strtotime($endDates); //结束
        while(true){
            if ($bof > $eof) break;
            $time = $bof;
            $start = date('Y-m-d 00:00:00',$time);
            $end = date('Y-m-d 23:59:59',$time);
            $day = date('Ymd',$time);

            DB::beginTransaction();
            try{

                //清空平台日销售额表(shopify)
                SalesAmountDay::query()->where('plat_id',$shopifyPlat)->where('day',$day)->update(['amount'=>0,'promotion_discount'=>0]);
                $shopifyCountryId = 1; //US
                $shopifyCurrency = [];
                $shopifySku = [];
                ShopifyOrder::query()
                    ->where('purchase_at','>=',strtotime($start))
                    ->where('purchase_at','<=',strtotime($end))
                    ->orderBy('id')
                    ->chunk(500, function ($aOrders) use(&$shopifyCountryId,&$shopifyCurrency,&$shopifySku,$day,$time,$shopifyPlat){
                        foreach ($aOrders as $aOrder){
                            foreach ($aOrder->shopify_orders_items as $item){
                                if(is_null($item->currency))continue;
                                $amount = SalesAmountDay::query()
                                    ->where('plat_id',$shopifyPlat)
                                    ->where('country_id',$shopifyCountryId)
                                    ->where('seller_sku',$item->sku)
                                    ->where('day',$day)
                                    ->first();
                                if($amount){
                                    $amount->amount += ($item->price ?: 0);
                                    $amount->promotion_discount += ($item->discount_allocations ?: 0);
                                    $amount->save();
                                }else{
                                    if(!array_key_exists($item->currency,$shopifyCurrency)){
                                        $shopifyCurrency[$item->currency] = ExchangeRate::getRateOddsToRMB($item->currency,$time);
                                    }
                                    if(!array_key_exists($item->sku,$shopifySku)){
                                        //$pSkuId = ProductShopifySku::query()->where('seller_sku',$item->sku)->value('psku_id');
                                        $pSkuId = ProductSku::query()->where('psku_code',$item->sku)->value('id');
                                        $shopifySku[$item->sku] = $pSkuId ?: 0;
                                    }
                                    SalesAmountDay::query()->create([
                                        'plat_id'    => $shopifyPlat,
                                        'country_id' => $shopifyCountryId,
                                        'seller_sku' => $item->sku,
                                        'day' => $day,
                                        'account_id' => $item->account_id, //shopify账号
                                        'psku_id' => $shopifySku[$item->sku],
                                        'amount' => $item->price ?: 0,
                                        'promotion_discount' => $item->discount_allocations ?: 0,
                                        'rate_odds' => $shopifyCurrency[$item->currency]
                                    ]);
                                }
                            }
                        }
                    });
                sleep(2);

                DB::commit();
            }catch (\Exception $e){
                DB::rollBack();
                report($e);
            }

            echo $day.PHP_EOL;
            $bof += 60*60*24;

            sleep(2);
        }
    }
}
